package com.bookstore.spring.action;

import com.bookstore.spring.pojo.ShoppingCart;
import com.bookstore.spring.service.CashService;
import com.bookstore.spring.web.BookStoreWebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Admin on 2016/8/23.
 */
public class CashAction {
    private CashService cashService;

    public ModelAndView toCash(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ModelAndView mv = new ModelAndView("/WEB-INF/page/cash");
        return mv;
    }

    public ModelAndView cash(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 简单验证: 验证表单域的值是否符合基本的规范: 是否为空, 是否可以转为 int 类型,
        // 是否是一个 email. 不需要进行查询数据库或调用任何的业务方法.

        String username = request.getParameter("username");
        String accountId = request.getParameter("accountId");

        StringBuffer error = cashService.validateFormField(username, accountId);

        if(error.toString().equals("")){
            error=cashService.validateUser(username, accountId);
            if(error.toString().equals("")){
                error=cashService.validateStoreNumber(request);
                if(error.toString().equals("")){
                    error=cashService.validateBalance(request,accountId);
                }
            }
        }
        if (!error.toString().equals("")) {
            ModelAndView mv = new ModelAndView("/WEB-INF/page/cash");
            mv.addData("error", error);
            return mv;
        }
        ShoppingCart shoppingCart= BookStoreWebUtils.getShoppingCart(request);
        cashService.cash(shoppingCart,username,accountId);
        ModelAndView mv = new ModelAndView(request.getContextPath() +"/success2",ModelAndView.REDIRECT);
        return mv;

    }

    public CashService getCashService() {
        return cashService;
    }

    public void setCashService(CashService cashService) {
        this.cashService = cashService;
    }
}